package com.lhb.service.Impl;

import com.lhb.dao.PermissionDao;
import com.lhb.dao.PermissionMapper;
import com.lhb.dao.Repository.PermissionRepository;
import com.lhb.pojo.BaseResp;
import com.lhb.pojo.TbPermission;
import com.lhb.pojo.TbRole;
import com.lhb.pojo.resp.TbPermissionResp;
import com.lhb.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.10.13 下午 17:30
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionRepository permissionRepository;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    PermissionDao permissionDao;

    @Override
    public BaseResp findAll(Integer page, Integer limit) {
        PageRequest of = PageRequest.of(page - 1, limit);
        Page<TbPermission> all = permissionRepository.findAll(of);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setMsg("success");
        baseResp.setCount(all.getTotalElements());
        baseResp.setData(all.getContent());
        return baseResp;
    }

    @Override
    public BaseResp findByRole(Integer roleid) {
        //查询并解析，循环判断该角色是否拥有该权限，如果拥有该权限，则设置 checeked = true
        //1.查询所有的权限
        List<TbPermissionResp> all = permissionMapper.findAll();
        //2.通过角色ID查询出该角色拥有的权限
        List<TbPermissionResp> rolePermission = permissionMapper.findByRoleId(roleid);

        for (TbPermissionResp tb : all) {
            for (TbPermissionResp rp : rolePermission
            ) {
                if (tb.getTitle().equals(rp.getTitle())) {
                    tb.setChecked(true);
                    break;
                }
            }
        }
        BaseResp baseResp = new BaseResp();
        baseResp.setData(all);
        baseResp.setCode(0);
        return baseResp;
    }

    @Override
    public BaseResp updatePer(TbPermission tbPermission) {
        int i = permissionDao.updatePer(tbPermission);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setMsg("修改成功");
        return baseResp;
    }

    @Override
    public BaseResp AddPermission(TbPermission tbPermission) {
        int i = permissionDao.AddPermission(tbPermission);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setMsg("添加成功");
        return baseResp;
    }

    @Override
    public void deleteById(Integer id) {
        permissionRepository.deleteById(id);
    }
}

